import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        title: 'Material App',
        home: Scaffold(
          appBar: AppBar(
            title: Text('Material App Bar'),
          ),
          body: MyApp(),
        ),
      ),
    );


/// 不能和MaterialApp写在同一层级
/// 因为MaterialApp里包含Navigator导航,更上层就找不到了
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: TextButton(
          child: Text('显示弹窗'),
          onPressed: () {
            BdDialog.show(context, '美女, 交个朋友');
          },
        ),
      ),
    );
  }
}

/// 透明背景的弹窗
class BdDialog {
  static void show(BuildContext context, String msg) {
    Navigator.of(context).push(_DialogRouter(_TextDialog(msg)));
    // 两秒后消失
    Future.delayed(Duration(seconds: 2)).then((value) {
      if (Navigator.canPop(context)) {
        Navigator.of(context).pop();
      }
    });
  }

  static void hide(BuildContext context) {
    Navigator.of(context).pop();
  }
}

/// 文字弹窗
class _TextDialog extends Dialog {
  final String msg;

  _TextDialog(this.msg);

  @override
  Widget build(BuildContext context) {
    return Material(
      //创建透明层
      type: MaterialType.transparency, //透明类型
      child: Center(
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
          child: Text(
            msg,
            style: TextStyle(color: Colors.white),
          ),
          decoration: BoxDecoration(
            color: Colors.black87,
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
        ),
      ),
    );
  }
}

/// 弹窗路由
class _DialogRouter extends PageRouteBuilder {
  final Widget page;

  _DialogRouter(this.page)
      : super(
            opaque: false,
            barrierColor: Color(0x00000001),
            pageBuilder: (context, animation, secondaryAnimation) => page,
            transitionsBuilder:
                (context, animation, secondaryAnimation, child) => child);
}
